package com.dongdongshop.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*
    *生成ShiroFilterFactoryBean安全管理
    * */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        /*设置安全管理器*/
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
        /*设置过滤和拦截*/
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/login/**","anon");
        map.put("/index/**","anon");
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        /*关联AdminRealm*/
        defaultWebSecurityManager.setRealm(getAdminRealm());
        return defaultWebSecurityManager;
    }

    @Bean
    public AdminRealm getAdminRealm(){
        AdminRealm adminRealm = new AdminRealm();
        /*加密方式*/
        adminRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return adminRealm;
    }

    /*配置加密方式*/
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        /*指定加密方式*/
        credentialsMatcher.setHashAlgorithmName("MD5");
        /*加密次数*/
        credentialsMatcher.setHashIterations(3);
        /*设置编码,true表示hex编码,false表示base64位编码*/
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return  credentialsMatcher;
    }

}
